<template>
  <!-- 承运商对账单的详情页,可以在这里创建对账单 -->
  <div>
    <div class="detailContainer" v-show="checkType !== 'add'">
      <div class="searchContainer">
        <el-form ref="form" :model="searchData" :inline="true">
          <el-form-item label="承运商名称" size="mini" style="width: 290px">
            <el-select
              disabled
              v-model="searchData.carrier_id"
              style="width: 200px"
            >
              <el-option
                v-for="carrier in carrierList"
                :key="carrier.id"
                :label="carrier.name"
                :value="carrier.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运单创建时间" size="mini" style="width: 320px">
            <el-date-picker
              v-model="searchData.waybillCreateTime"
              type="daterange"
              value-format="timestamp"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              :default-time="['00:00:00', '23:59:59']"
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="对账状态" size="mini" style="width: 270px">
            <el-select v-model="searchData.account_status" style="width: 200px">
              <el-option label="未对账" value="0" />
              <el-option label="已对账" value="1" />
              <el-option label="全部" value="" />
            </el-select>
          </el-form-item>
          <el-form-item label="批次号" size="mini" style="width: 290px">
            <el-input
              v-model="searchData.batch_number"
              style="width: 230px"
              placeholder="请输入批次号"
            ></el-input>
          </el-form-item>
          <el-form-item label="出发省市" size="mini" style="width: 290px">
            <el-input
              v-model="searchData.from_address"
              placeholder="请输入出发省市"
            ></el-input>
            <!-- <el-cascader
            :options="addresssequence"
            v-model="searchData.from_address"
            placeholder="请选择省市区"
            :props="{
              value: 'id',
              label: 'name',
              children: 'next_level_data',
            }" 
          </el-cascader> -->
          </el-form-item>
          <el-form-item label="目的省市" size="mini" style="width: 290px">
            <el-input
              v-model="searchData.to_address"
              placeholder="请输入目的省市"
            ></el-input>
            <!-- <el-cascader
            :options="addresssequence"
            v-model="searchData.to_address"
            placeholder="请选择省市区"
            :props="{
              value: 'id',
              label: 'name',
              children: 'next_level_data',
            }"
          ></el-cascader> -->
          </el-form-item>
          <el-form-item label="负责区域" size="mini" style="width: 290px">
            <!-- <el-input
              v-model="searchData.branch_id"
              placeholder="请输入批次号"
            ></el-input> -->
            <el-select v-model="searchData.branch_id" style="width: 200px">
              <el-option
                v-for="bigArea in bigAreaList"
                :key="bigArea.id"
                :label="bigArea.name"
                :value="bigArea.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="批次类型" size="mini" style="width: 285px">
            <el-select v-model="searchData.batch_type" style="width: 215px">
              <el-option label="揽收" value="1" />
              <el-option label="干线" value="2" />
              <el-option label="配送" value="3" />
              <el-option label="回单" value="4" />
              <el-option label="回箱" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="运单号" size="mini">
            <el-input
              v-model="searchData.waybill_no"
              style="width: 230px"
              placeholder="请输入运单号"
            ></el-input>
          </el-form-item>
          <el-form-item label="运单所属客户" size="mini">
            <!-- <el-select v-model="searchData.customer_id" style="width: 200px">
              <el-option
                  v-for="item in customerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
            </el-select> -->
            <el-select v-model="searchData.customer_id" remote reserve-keyword :remote-method="searchCustomerList"
            filterable placeholder="请选择"  style="width: 165px;">
            <el-option v-for="item2 in client" :key="item2.id" :label="item2.name" :value="item2.id">
            </el-option>
          </el-select>
          </el-form-item>
          <el-form-item size="mini">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="searchSenderCheckDetailList"
              >查询</el-button
            >
            <el-button plain icon="el-icon-refresh-left" @click="resettingData"
              >重置</el-button
            >
            <el-button
              plain
              icon="el-icon-d-arrow-left"
              @click="changeCarrierDetailPage(false)"
              >返回承运商对账列表</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="operation">
        <el-button
          plain
          type="primary"
          @click="createCheckList"
          style="margin-left: 10px"
          data-tracker="P48-8"
          v-permission="'finance_customer_create'"
          >创建对账单</el-button
        >
        <el-tag style="margin-left: 10px"
          ><span>已对账合计：</span>
          <span>{{ alAccount ? alAccount : 0 }}，</span>
          <span>未对账合计：</span>
          <span>{{ noAccount ? noAccount : 0 }}</span></el-tag
        >
      </div>
      <el-table
        ref="multipleTable"
        :data="spanVal"
        :row-key="(item) => `${item.relation_id}+${item.waybill_id}`"
        border
        align="center"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        max-height="480px"
        :span-method="objectSpanMethod"
      >
        <el-table-column type="selection" width="45" :reserve-selection="true">
        </el-table-column>
        <el-table-column prop="index" fixed label="序号" width="50">
          <template slot-scope="scope">
            {{ scope.row.index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="relation_no" fixed label="批次号" width="180">
        </el-table-column>
        <el-table-column prop="node_type" fixed label="批次类型" width="70">
          <template slot-scope="scope">
            {{
              scope.row.node_type === "1"
                ? "揽收"
                : scope.row.node_type === "2"
                ? "干线"
                : scope.row.node_type === "3"
                ? "配送"
                : scope.row.node_type === "4"
                ? "回单"
                : "回箱"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="对账状态" width="70">
          <template slot-scope="scope">
            {{ scope.row.status === "0" ? "未对帐" : "已对帐" }}
          </template>
        </el-table-column>
        <el-table-column prop="from_address" label="出发省市" width="300">
        </el-table-column>
        <el-table-column prop="to_address" label="目的省市" width="300">
        </el-table-column>
        <el-table-column prop="branch_id_name" label="负责区域" width="100">
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100">
        </el-table-column>
        <el-table-column prop="total_expenses" label="总费用" width="150">
        </el-table-column>
        <el-table-column prop="waybill_no" label="运单号" width="150">
          <template slot-scope="scope">
            <div
              style="cursor: pointer; color: blue"
              @click="handleJump(scope)"
            >
              {{ scope.row.waybill_no }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="collect_money" label="提货揽收费" width="150">
        </el-table-column>

        <el-table-column prop="package_money" label="揽收包装费" width="150">
        </el-table-column>
        <el-table-column prop="handling_money" label="揽收装卸费" width="150">
        </el-table-column>
        <el-table-column prop="delivery_money" label="揽收发货费" width="150">
        </el-table-column>
        <el-table-column
        prop="airport_pick_money"
        label="揽收机场提货费"
        width="150"
          >
          </el-table-column>
          <el-table-column
          prop="dry_ice_money"
          label="揽收干冰费"
          width="150"
        >
        </el-table-column>
        <el-table-column prop="transport_fee" label="运输费" width="150">
        </el-table-column>
        <el-table-column prop="delivery_fee" label="配送费" width="150">
        </el-table-column>
        <el-table-column
          prop="extra_distribution_fee"
          label="配送里程费"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="second_distribution_fee"
          label="二次配送费"
          width="150"
        >
        </el-table-column>
        <el-table-column prop="waiting_fee" label="配送专车费" width="150">
        </el-table-column>
        <el-table-column
          prop="airport_pick_fee"
          label="配送机场提货费"
          width="150"
        >
        </el-table-column>
        <el-table-column
        prop="dry_ice_fee"
        label="配送干冰费"
        width="150"
      >
      </el-table-column>
      <el-table-column prop="return_box_money" label="返箱费" width="150">
      </el-table-column>
      <el-table-column prop="airport_operate_fee" label="机场操作费" width="150">
      </el-table-column>
      <el-table-column prop="transfer_fee" label="中转费" width="150">
      </el-table-column>
        <el-table-column prop="return_receipt_fee" label="回单费用" width="150">
        </el-table-column>
        <el-table-column prop="return_box_fee" label="回箱费用" width="150">
        </el-table-column>
      
      </el-table>
    </div>
    <div v-show="checkType === 'add'">
      <carrierCheckDetail
        :closeCheckPage="closeCheckPage"
        :carrier_id="carrier_id"
        :selectedDetails="selectedDetails"
        :createTime="searchData.waybillCreateTime"
        :displayParentOrders="displayOrders"
      ></carrierCheckDetail>
    </div>
  </div>
</template>

<script>
import carrierCheckDetail from "./carrierCheckDetail.vue";
import tableForm from "@/components/table/table";
import pagination from "@/components/pagination";
import { reqCarrierSDetailList } from "@/api/finance";
import { regionList } from "@/page/material/common/common";
import {
  customerPeople,
} from "@/api/information";
export default {
  name: "carrierDetail",
  props: ["carrier_id", "createTime", "changeCarrierDetailPage"],
  data() {
    return {
      carrierList: [], //承运商名称
      searchData: {
        carrier_id: "", //承运商id
        waybillCreateTime: [],
        createTime: [
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 30),
          new Date().getTime(),
        ], //创建时间
        account_status: "0", //对账状态,默认未对账
        batch_number: "", //批次号
        batch_type: "", //批次类型
        waybill_no: "", //运单号
        from_address: "", //出发省市
        to_address: "", //目的省市
        branch_id: "", //负责区域
        customer_id:"",//运单所属客户
      }, //查询条件
      alAccount: "", //已对账
      noAccount: "", //未对账
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      tableData: [],
      selectedOrders: [], //选中的id
      selectedDetails: [], //选中的详细信息
      spanVal: [], //处理过的用于合并行的表格数据
      otherSpanVal: [], //记忆的已选中的数据
      bigAreaList: [], //区域列表
      addresssequence: [],
      client: [], //客户列表
    };
  },
  components: { tableForm, pagination, carrierCheckDetail },
  mounted() {
    this.getBigAreaList();
    this.provincectiy();
    this.getCarrierList();
  },
  watch: {
    createTime() {
      this.searchData.waybillCreateTime = this.createTime;
    },
    carrier_id() {
      Object.assign(this.$data.searchData, this.$options.data().searchData);
      this.searchData.carrier_id = this.carrier_id * 1;
      this.searchData.waybillCreateTime = this.createTime;
      this.displayOrders();
    },
  },
  computed: {
    checkType() {
      return this.$store.getters.checkType;
    },
  },
  methods: {
    async displayOrders() {
      const { searchData } = this;
      // console.log(searchData.from_address, "searchData.from_address");
      // console.log(searchData.to_address, "searchData.to_address");
      let result = await reqCarrierSDetailList({
        // header_id:40+"",
        carrier_id: String(this.carrier_id),
        status: searchData.account_status, //0是未对账,1是已对账
        node_type: String(searchData.batch_type),
        relation_no: String(searchData.batch_number), //批次号
        // start_time: String(parseInt(searchData.createTime[0] / 1000)),
        // end_time: String(parseInt(searchData.createTime[1] / 1000)),
        waybill_no: String(searchData.waybill_no),
        from_address: String(searchData.from_address),
        to_address: String(searchData.to_address),
        // to_address:String(searchData.to_address[1]),
        branch_id: String(searchData.branch_id),
        waybill_create_time: {
          start_time: searchData.waybillCreateTime[0]
            ? String(parseInt(searchData.waybillCreateTime[0] / 1000))
            : "",
          end_time: searchData.waybillCreateTime[1]
            ? String(parseInt(searchData.waybillCreateTime[1] / 1000))
            : "",
        customer_id:searchData.customer_id
        },
      });
      if (result.code === 10000) {
        this.tableData = result.data.data ? result.data.data.list : [];
        this.alAccount = result.data.data ? result.data.data.al_total : ""; //已对账
        this.noAccount = result.data.data ? result.data.data.un_total : ""; //未对账
        this.tableData.forEach((item, index) => {
          var param_id = []
          item.forEach((item2, index2) => {
            param_id.push(item2.id)
            //item2是合并行里面的运单数据
            if (index2 === 0) {
              this.$set(item2, "collapseNumber", item.length); //应该合并几列
              this.$set(item2, "time_id", param_id); //应该合并几列
            } else {
              this.$set(item2, "collapseNumber", 0); //其余的不显示，标为0
              this.$set(item2, "time_id", param_id); //应该合并几列
            }
            this.$set(item2, "index", index); //操作单的索引
          });
        });
        setTimeout(() => {
          this.spanVal = this.tableData.flat(2);
          console.log(this.spanVal,"this。spanValfalksdj")
        }, 500);
      } else {
        this.$message({
          type: "error",
          message: result.message,
        });
      }
    },
    resettingData() {
      Object.assign(this.$data.searchData, this.$options.data().searchData);
      this.searchData.waybillCreateTime = this.createTime;

      this.displayOrders();
    },
    async handleJump(scope) {
      //跳转到对应运单详情
      const checkedOrder = scope.row;
      const { waybill_id } = checkedOrder;
      let text = this.$router.resolve({
        name: "waybillDetail",
        query: { id: waybill_id, activeName: "1" },
      });
      window.open(text.href, "_blank");
    },
    async getCarrierList() {
      setTimeout(() => {
        this.carrierList = this.$store.getters.carrierList;
      }, 1000);
    },
    searchSenderCheckDetailList() {
      //查询功能
      this.displayOrders();
    },
    createCheckList() {
      let arrs = this.spanVal.filter((x) => 
        this.selectedOrders.some((item) => (item.relation_id === x.relation_id && item.node_type == x.node_type))
      ); //从table表格收集所有被拆分的揽收单
      console.log(arrs,"arrsarrsarrsarrs")
      this.otherSpanVal = arrs;
      this.selectedDetails = [...this.otherSpanVal];
      //创建对账单,判断一下所选订单的对账状态,已对过账的提醒一下
      // console.log(this.selectedDetails, "this.selectedDetails");
      if (this.selectedDetails.length !== 0) {
        if (
          this.selectedDetails.every(
            (item) => item.status === "0" //0是未对账
          )
        ) {
          this.$store.commit("CHANGE_CHECK_TYPE", "add");
        } else {
          this.$message({
            type: "error",
            message: "只能选择未对账的运单",
          });
        }
      } else {
        this.$message({
          type: "error",
          message: "至少选择一个运单",
        });
      }
    },
    handleSelectionChange(checked) {
      console.log(checked,"carrierreconciliation")
      //因为这里只选中了合并的操作单里面的第一条运单
      // this.selectedOrders = checked.map((item) => item.id);
      this.selectedOrders = checked
      console.log(this.selectedOrders)
      // console.log()
    },
    closeCheckPage() {
      this.$store.commit("CHANGE_CHECK_TYPE", "");
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(row.collapseNumber,'rowfasdfasdf')
      if (
        columnIndex === 0 ||
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 4 ||
        columnIndex === 5 ||
        columnIndex === 6 ||
        columnIndex === 7
      ) {
        //列的index
        //当xxx的时候合并rowspan行0列
        if (row.collapseNumber > 0) {
          return {
            rowspan: row.collapseNumber,
            colspan: 1,
          };
        } else {
          return {
            //表示这一行不显示
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    async getBigAreaList() {
      setTimeout(() => {
        this.bigAreaList = this.$store.getters.websiteList;
      }, 1000);
    },
    // 地址库
    provincectiy() {
      regionList(0).then((res) => {
        this.addresssequence = this.getFirstTwoLevels(res.data);
        // this.addresssequence = res.data;
        // console.log(this.addresssequence, "地址库的调用");
      });
    },
    getFirstTwoLevels(data) {
      var result = [];
      for (var i = 0; i < data.length; i++) {
        var firstLevel = {
          id: data[i].id,
          name: data[i].name,
        };

        var secondLevelData = data[i].next_level_data;
        if (secondLevelData) {
          var secondLevel = [];
          for (var j = 0; j < secondLevelData.length; j++) {
            secondLevel.push({
              id: secondLevelData[j].id,
              name: secondLevelData[j].name,
            });
          }
          firstLevel.next_level_data = secondLevel;
        }

        result.push(firstLevel);
      }
      return result;
    },
       // 模糊搜索
    searchCustomerList(val, id) {
      var param = {
        name: val + "",
        is_send: "1",
        is_receive: "",
        id: id == undefined ? "" : id + "",
      };
      customerPeople(param).then((res) => {
        var res = res.data;
        this.client = res;
      });
    },
  },
};
</script>

<style scoped lang="less">
.detailContainer {
  background-color: #fff;

  .searchContainer {
    padding: 0 20px;
    border-bottom: 7px solid #e8f1f7;
    .el-form-item--mini.el-form-item {
      margin-bottom: 10px;
    }
  }
  .operation {
    padding-top: 10px;
    height: 40px;
    ::v-deep .el-pagination {
      float: right;
      .el-input--mini .el-input__inner {
        height: 24px;
      }
    }
    .el-tag {
      height: 30px;
      padding: 5px 30px;
      border-color: #92d6ff;
      background-color: #e6f7ff;
      span {
        font-weight: bold;
        color: black;
      }
    }
  }
  .cutPages {
    height: 40px;
  }
}
</style>